package order

import (
	"booking/common/handler"
	"booking/common/validator"
	"booking/models"
	"time"

	"github.com/gin-gonic/gin"
	jsoniter "github.com/json-iterator/go"
)

func Shipped(c *gin.Context) {
	var params struct {
		OrderNo     string               `json:"order_no" binding:"required"`
		Courier     string               `json:"courier" binding:"required"`
		TrackingNo  string               `json:"tracking_no" binding:"required"`
		Attachments []models.Attachments `json:"attachments"`
	}

	if err := c.ShouldBindJSON(&params); err != nil {
		handler.Error(validator.Translate(err), c)
		return
	}
	var order models.Order
	models.Db.Model(models.Order{}).
		Where(map[string]any{
			"order_no": params.OrderNo,
		}).
		First(&order)
	if order.Id == 0 {
		handler.Error("订单不存在", c)
		return
	}
	var orderAttachments []models.Attachments
	jsoniter.UnmarshalFromString(order.Attachments, &orderAttachments)
	orderAttachments = append(orderAttachments, params.Attachments...)
	orderAttachmentsJson, _ := jsoniter.MarshalToString(orderAttachments)

	tx := models.Db.Begin()
	defer func() {
		if r := recover(); r != nil {
			tx.Rollback()
		}
	}()
	err := tx.Model(models.Order{}).Where(map[string]any{
		"order_no": params.OrderNo,
	}).Updates(map[string]any{
		"status":      models.OrderStatusShipping,
		"attachments": orderAttachmentsJson,
		"push_time":   time.Now().Format("2006-01-02 15:04:05"),
	}).Error
	if err != nil {
		tx.Rollback()
		handler.Error(err.Error(), c)
		return
	}
	attachments, _ := jsoniter.MarshalToString(&params.Attachments)
	var nowTime = time.Now()
	var orderCourier models.OrderCourier = models.OrderCourier{
		OrderNo:       order.OrderNo,
		Courier:       params.Courier,
		CourierStatus: models.CourierStatusShipped,
		ShipTime:      &nowTime,
		TrackingNo:    params.TrackingNo,
		Attachments:   attachments,
	}
	err = tx.Model(models.OrderCourier{}).Create(&orderCourier).Error
	if err != nil {
		tx.Rollback()
		handler.Error(err.Error(), c)
		return
	}
	if err := tx.Commit().Error; err != nil {
		handler.Error("保存失败: "+err.Error(), c)
		return
	}
	handler.Success(map[string]any{
		"order_no": order.OrderNo,
	}, c)

}
